package daoimpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import connector.Connector;
import daointerfaces.DALException;
import daointerfaces.RaavareBatchDAO;
import dto.RaavareBatchDTO;

public class MySQLRaavareBatchDAO implements RaavareBatchDAO {

	@Override
	public RaavareBatchDTO getRaavareBatch(int rbId) throws DALException {
		ResultSet rs = Connector.doQuery("SELECT * FROM raavareBatchCDIO WHERE rbId = " + rbId);
		try {
			if (!rs.first()) throw new DALException("RaavareBatch " + rbId + " findes ikke");
			return new RaavareBatchDTO(rs.getInt(1), rs.getInt(2), rs.getDouble(3), rs.getString(4), rs.getString(5));
		}
		catch (SQLException e) {throw new DALException(e); }
	}

	@Override
	public List<RaavareBatchDTO> getRaavareBatchList() throws DALException {
		List<RaavareBatchDTO> list = new ArrayList<RaavareBatchDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM raavareBatchCDIO");
		try
		{
			while (rs.next())
			{
				list.add(new RaavareBatchDTO(rs.getInt(1), rs.getInt(2), rs.getDouble(3), rs.getString(4), rs.getString(5)));
			}
		}
		catch (SQLException e) { throw new DALException(e); }
		return list;
	}

	@Override
	public List<RaavareBatchDTO> getRaavareBatchList(int raavareId)
			throws DALException {
		List<RaavareBatchDTO> list = new ArrayList<RaavareBatchDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM raavareBatchCDIO WHERE rbId= " + raavareId);
		try
		{
			while (rs.next()) 
			{
				list.add(new RaavareBatchDTO(rs.getInt(1), rs.getInt(2), rs.getDouble(3), rs.getString(4), rs.getString(5)));
			}
		}
		catch (SQLException e) { throw new DALException(e); }
		return list;
	}

	@Override
	public void createRaavareBatch(RaavareBatchDTO raavarebatch)
			throws DALException {
		Connector.doUpdate(
				"INSERT INTO raavareBatchCDIO(rbId, raavareId, maengde, leverandoer, leveringsDato) VALUES " +
						"(" + raavarebatch.getRbId() + ", " + raavarebatch.getRaavareId() + ", " + raavarebatch.getMaengde() 
						+ ", '" + raavarebatch.getRaavareBatchLeverandoer()+ "', '"+raavarebatch.getLeveringsDato()+"')"
				);
	}

	public void deleteRaavareBatch(int rbId) throws DALException {
		Connector.doUpdate(
				"DELETE FROM raavareBatchCDIO WHERE rbId=" + rbId
				);
	}

	@Override
	public void updateRaavareBatch(RaavareBatchDTO raavarebatch)
			throws DALException {
		Connector.doUpdate(
				"UPDATE raavareBatchCDIO SET  rbId = " + raavarebatch.getRbId() + ", raavareId = " + raavarebatch.getRaavareId() + 
				", maengde =  " + raavarebatch.getMaengde() + ", leverandoer = '" + raavarebatch.getRaavareBatchLeverandoer() + "', leveringsDato = '"+ raavarebatch.getLeveringsDato() +"' WHERE rbId =  "  
				+ raavarebatch.getRbId()
				);
	}
}
